package cn.wit.summit.chwan.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.core.ImagePipeline;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.dot.DotService;
import cn.wit.summit.chwan.models.response.ChangeIconResponse;
import cn.wit.summit.chwan.models.response.CodeloginRespone;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.ui.base.MyActivity;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.FileUtil;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.ToastUtils;
import cn.wit.summit.chwan.utils.UtilsMy;
import cn.wit.summit.chwan.widgets.CurrencyPromptDialog;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/7/5.
 */

public class SetPersonalInformationActivity extends MyActivity {

    @Bind(R.id.personalInfoIconIv)
    SimpleDraweeView personalInfoIconIv;
    @Bind(R.id.personalInfoNickEt)
    EditText personalInfoNickEt;
    @Bind(R.id.personalInfoSubBt)
    Button personalInfoSubBt;

    private AccountBean accountBean;

    private Dialog mPicChsDialog;
    private static final int CAPTURE_IMAGE_CAMERA = 100;
    private static final int IMAGE_STORE = 200;
    private static final int CROP_CHOOSE = 10;
    private int index;
    private Uri fileUri, cropUri;
    private boolean granted;
    private boolean granted2;
    private String nickStr = "";

    private RetrofitManager retrofitManager;
    private Retrofit retrofitLogin;
    private ApiUtil apiLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_personal_information);
        ButterKnife.bind(this);

        retrofitManager = RetrofitManager.getInstance(mContext);
        retrofitLogin = retrofitManager.getLoginRetrofit();
        apiLogin = retrofitLogin.create(ApiUtil.class);

        setBarTitleTx(R.string.set_persoanl_info_title);
        getBarBackLl().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                exitClick();
            }
        });

        accountBean = (AccountBean) getIntent().getSerializableExtra("login_data");
    }

    @OnClick({R.id.personalInfoIconIv, R.id.personalInfoSubBt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.personalInfoIconIv:
                ChangIcon();
                break;
            case R.id.personalInfoSubBt:
                if (cropUri==null) {
                    showToast("请选择头像！");
                    return;
                }
                nickStr = personalInfoNickEt.getText().toString().trim();
                if (StringUtils.isEmpty(nickStr)) {
                    showToast(mContext.getResources().getString(R.string.dialog_add_nick_wran));
                    return;
                }
                if (!StringUtils.matchStringLength(nickStr, 4, 16)){
                    showToast("昵称格式有误，输入4至16位字母或2至8汉字");
                    return;
                }
                hideSoftInput(personalInfoNickEt);
                toUpImage();
                break;
        }
    }

    /**
     * 修改头像
     */
    private void ChangIcon() {
        mPicChsDialog = new Dialog(mContext, R.style.floate_dialog);
        mPicChsDialog.setContentView(R.layout.dialog_pic_choose);
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        Window dlgwin = mPicChsDialog.getWindow();
        WindowManager.LayoutParams lp = dlgwin.getAttributes();
        dlgwin.setGravity(Gravity.BOTTOM);
        lp.width = display.getWidth(); //设置宽度
        mPicChsDialog.getWindow().setAttributes(lp);
        TextView camera = (TextView) mPicChsDialog.findViewById(R.id.chos_camera);
        TextView picLib = (TextView) mPicChsDialog.findViewById(R.id.pic_lib);
        TextView cancel = (TextView) mPicChsDialog.findViewById(R.id.btn_cancel);
        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getPicFrom(CAPTURE_IMAGE_CAMERA);
                mPicChsDialog.dismiss();
            }
        });

        picLib.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getPicFrom(IMAGE_STORE);
                mPicChsDialog.dismiss();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPicChsDialog.dismiss();
            }
        });
        mPicChsDialog.show();
    }

    /**
     * 获取图片资源
     *
     * @param type 类型（本地IMAGE_STORE/拍照CAPTURE_IMAGE_CAMERA）
     */
    private void getPicFrom(int type) {
        String path = Environment.getExternalStorageDirectory() + "/chwdownload/imageupload";
        File f = new File(path);
        if (!f.exists()) {
            f.mkdirs();
        }
        File[] fs = f.listFiles();
        if (fs != null) {
            for (File fi : fs) {
                if (fi.exists() && fi.isFile() && fi.getName().endsWith(".jpg")) {
                    UtilsMy.delete(fi);
                }
            }
        }
        switch (type) {
            case CAPTURE_IMAGE_CAMERA:
                index = 1;
                if (Build.VERSION.SDK_INT >= 23) {
                    int permission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA);
                    if (permission != PackageManager.PERMISSION_GRANTED) {
                        checkPublishPermission(index);
                        if (granted == false) {
                            return;
                        }
                    }
                }
                Intent intent_photo = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent_photo.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    fileUri = FileProvider.getUriForFile(mContext, "cn.wit.summit.chwan.fileprovider", getfileAbsupath(""));
                } else {
                    fileUri = createCoverUri("");
                }
                Log.e("TAG", "FF:" + fileUri);
                intent_photo.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                intent_photo.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                startActivityForResult(intent_photo, CAPTURE_IMAGE_CAMERA);
                Log.e("TAG", "2");

                break;
            case IMAGE_STORE:
                index = 2;
                if (Build.VERSION.SDK_INT >= 23) {
                    if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        checkPublishPermission(index);
                        if (granted2 == false) {
                            return;
                        }
                    }
                }

                fileUri = createCoverUri("_select");
//                Intent intent_album = new Intent("android.intent.action.GET_CONTENT");
//                intent_album.setType("image/*");
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, IMAGE_STORE);
                break;

        }
    }

    private File getfileAbsupath(String type) {
        String filename = AccountUtil.getInstance().getUid() + type + System.currentTimeMillis() + ".jpg";
        String path = Environment.getExternalStorageDirectory() + "/chwdownload/imageupload";
        Log.e("TAG", "拍照1" + path.toString());
        File outputImage = new File(path, filename);
        try {
            File pathFile = new File(path);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            if (outputImage.exists()) {
                outputImage.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
            showToast("生成封面失败");
        }

        return outputImage;
    }

    private Uri createCoverUri(String type) {
        String filename = AccountUtil.getInstance().getUid() + type + System.currentTimeMillis() + ".jpg";
        String path = Environment.getExternalStorageDirectory() + "/chwdownload/imageupload";
        Log.e("TAG", "拍照1" + path.toString());
        File outputImage = new File(path, filename);
        try {
            File pathFile = new File(path);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            if (outputImage.exists()) {
                outputImage.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
            showToast("生成封面失败");
        }

        return Uri.fromFile(outputImage);
    }

    private void checkPublishPermission(int type) {
        switch (type) {
            case 1:
                //拍照
                int permission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA);
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    //去申请
                    if (shouldRequest(1)) return;
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
                }
                break;
            case 2:
                //从相册选择
                if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    if (shouldRequest(2)) return;
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                }
                break;
        }
    }

    private boolean shouldRequest(int o) {
        if (o == 1) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                //显示一个对话框，给用户解释
                explainDialog(o);
                return true;
            }
        } else if (o == 2) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                //显示一个对话框，给用户解释
                explainDialog(o);
                return true;
            }
        }
        return false;
    }

    private void explainDialog(int i) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        if (i == 1) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
        } else if (i == 2) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults.length > 0) {
            if (index == 1){
                granted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                if (granted==false)
                    ToastUtils.getInstance(mContext).showToastSystem("权限不足");
            }else if (index ==2){
                granted2 = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                if (granted2==false)
                    ToastUtils.getInstance(mContext).showToastSystem("权限不足");
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CAPTURE_IMAGE_CAMERA:
                    startPhotoZoom(fileUri);
                    break;
                case IMAGE_STORE:
                    String path = FileUtil.getPath(this, data.getData());
                    if (null != path) {
                        File file = new File(path);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            startPhotoZoom(FileProvider.getUriForFile(mContext, "cn.wit.summit.chwan.fileprovider", file));
                        } else {
                            startPhotoZoom(Uri.fromFile(file));
                        }

                    }
                    break;
                case CROP_CHOOSE:
                    ImagePipeline imagePipeline = Fresco.getImagePipeline();
                    imagePipeline.evictFromMemoryCache(cropUri);
                    imagePipeline.evictFromDiskCache(cropUri);
                    imagePipeline.evictFromCache(cropUri);

                    DraweeController controller=Fresco.newDraweeControllerBuilder()
                            .setUri(cropUri)
                            .setAutoPlayAnimations(true)
                            .build();
                    personalInfoIconIv.setController(controller);
            }
        }
    }

    private void toUpImage() {
        //上传头像
        if (NetWorkUtils.isNetworkConnected(mContext)) {
            File file = new File(cropUri.getPath());
            MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);//表单类型
            RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            builder.addFormDataPart("files", file.getName(), imageBody);//imgfile 后台接收图片流的参数名

            MultipartBody.Part part = builder.build().part(0);
            String token = MyApplication.accountBean.getToken();
            if (token==null){
                showToast("Token为空");
                return;
            }
            showLoading("正在上传", false);
            RequestBody tokenBody = RequestBody.create(MediaType.parse("form-data"), token);
            apiLogin.getChangeIcon(part, MyApplication.accountBean.getUid(), tokenBody)
                    .enqueue(new Callback<ChangeIconResponse>() {
                        @Override
                        public void onResponse(Call<ChangeIconResponse> call, Response<ChangeIconResponse> response) {
                            if (call.isCanceled()) return;
                            ChangeIconResponse model = response.body();
                            if (model.getCode() == 600) {
                                accountBean.setAvatar(model.getData_info().getAvatarImg());
                                personalInfoIconIv.setImageURI(accountBean.getAvatar());
                                setNetChangeName();
                            } else {
                                cancelLoading();
                                showToast("头像上传失败，请重试！");
                            }
                        }

                        @Override
                        public void onFailure(Call<ChangeIconResponse> call, Throwable t) {
                            if (call.isCanceled()) return;
                            cancelLoading();
                            showToast("头像上传失败，请重试！");
                        }
                    });
        } else {
            cancelLoading();
            showToast("网络连接失败，再试试吧~");
        }
    }

    public void startPhotoZoom(Uri uri) {
        cropUri = createCoverUri("_crop");
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 340);
        intent.putExtra("aspectY", 290);
        intent.putExtra("outputX", 340);
        intent.putExtra("outputY", 290);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);//去黑边
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }

        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent, CROP_CHOOSE);
    }

    /**
     * 上传网名
     */
    private void setNetChangeName() {
        if (NetWorkUtils.isNetworkConnected(mContext)) {
            int uid = MyApplication.accountBean.getUid();
            String token = MyApplication.accountBean.getToken();
            if (token==null){
                showToast("Token为空");
                cancelLoading();
                return;
            }
            apiLogin.modifyNick(nickStr, uid+"", token).enqueue(new MyCallback<ResponseBase<CodeloginRespone>>() {
                @Override
                public void onSuccess(ResponseBase<CodeloginRespone> model) {
                    cancelLoading();
                    showToast("用户信息设置成功！");
                    accountBean.setNickname(nickStr);
                    accountBean.setDefaultNickname(1);
                    AccountUtil.getInstance().saveAccountData(accountBean);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            finish();
                        }
                    }, 500);
                }

                @Override
                public void onFailure(int code, String msg) {
                    cancelLoading();
                    showToast(msg);
                }
            });
        } else {
            cancelLoading();
            showToast("网络连接失败，再试试吧~");
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {// 返回键
            exitClick();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exitClick() {
        hideSoftInput(personalInfoNickEt);
        final CurrencyPromptDialog dialog = new CurrencyPromptDialog(mContext);
        dialog.show();
        dialog.setTitle(getResources().getString(R.string.comment_dialog_title_str));
        dialog.setMsg(getResources().getString(R.string.set_persoanl_info_dialog_msg_str));
        dialog.setCancleBtn(getResources().getString(R.string.set_persoanl_info_dialog_cancle_str), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService(new Intent(mContext, DotService.class));
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                        exitApp();
                        System.exit(0);
                    }
                }, 200);
            }
        });
        dialog.setOkBtn(getResources().getString(R.string.comment_dialog_ok_str), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }
}
